package com.xckj.cycling.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.junca.android.base.CViewBinding
import com.xckj.cycling.framework.MvvmUtils.lazyViewModel
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.lihang.chart.utils.ChartLineItem
import com.mapbox.api.directions.v5.DirectionsCriteria
import com.mapbox.api.directions.v5.models.RouteOptions
import com.mapbox.geojson.Point
import com.mapbox.navigation.base.extensions.applyDefaultNavigationOptions
import com.mapbox.navigation.base.route.NavigationRoute
import com.mapbox.navigation.base.route.NavigationRouterCallback
import com.mapbox.navigation.base.route.RouterFailure
import com.mapbox.navigation.base.route.RouterOrigin
import com.mapbox.navigation.utils.internal.toPoint
import com.xckj.cycling.R
import com.xckj.cycling.adapter.ImageAdapter
import com.xckj.cycling.databinding.ActivityRouteLineDetailBinding
import com.xckj.cycling.databinding.ListItemCommentBinding
import com.xckj.cycling.databinding.ListItemGailouCommentBinding
import com.xckj.cycling.dialog.AddCommentDialog
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.model.Comment
import com.xckj.cycling.model.RouteLineListModel
import com.xckj.cycling.model.RouteLineModel
import com.xckj.cycling.repository.MapRepository
import com.xckj.cycling.utils.distance
import com.xckj.cycling.utils.getCardBg
import com.xckj.cycling.utils.loadHead
import com.xckj.cycling.view.RouteMapView
import com.xckj.cycling.viewmodel.MapViewModel
import com.xckj.cycling.viewmodel.NavigationToStartViewModel
import com.xckj.cycling.viewmodel.RouteLineViewModel
import kotlinx.coroutines.launch
import java.math.RoundingMode

/**
 * 线路详情
 */
class RouteLineDetailActivity : BaseActivityKt(), AddCommentDialog.CommentCallback {

    private val data: RouteLineModel? by lazy {
        intent.getParcelableExtra("data")
    }
    private val routeLineViewModel: RouteLineViewModel by lazyViewModel()
    private val mapViewModel: MapViewModel by lazyGlobalViewModel()
    private val startViewModel: NavigationToStartViewModel by lazyGlobalViewModel()
    private var recid: String? = null

    @CViewBinding
    lateinit var viewBinding: ActivityRouteLineDetailBinding

    override fun initView(root: View, savedInstanceState: Bundle?) {
        super.initView(root, savedInstanceState)
        viewBinding.commentLl.background = getCardBg()
        if (data?.isuser == 1) {
            viewBinding.titlebar.tvRight.text = getString(R.string.edit)
            viewBinding.titlebar.tvRight.setOnClickListener {
                startActivity(
                    Intent(this, EditRouteActivity::class.java).putExtra(
                        "data",
                        model?.detail
                    )
                )
            }
        }
        load()
        viewBinding.comment.setOnClickListener {
            recid = null
            AddCommentDialog(this, this).show()
        }
    }

    private var model: RouteLineListModel? = null
    private fun load() {
        showLoading()
        routeLineViewModel.loadRouteDetail(data?.id ?: 0) {
            if (it.isSuccessful) {
                model = it.data
                it.data?.detail?.apply {
                    setData(this)
                    hideDialog()
                }
            }
        }
    }

    private fun setCollect(collectionnum: Int) {
//        viewBinding.detail.collection.isSelected = collect
//        viewBinding.detail.tvCollect.text =
//            if (collect) getString(R.string.collected) else getString(R.string.no_collect)
        viewBinding.detail.tvCollect.text = collectionnum.toString();
    }

    private fun setPraise(praisenum: Int) {
//        viewBinding.detail.praise.isSelected = praise
//        viewBinding.detail.tvPrice.text =
//            if (praise) getString(R.string.praised) else getString(R.string.no_praised)
        viewBinding.detail.tvPrice.text = praisenum.toString();
    }

    private fun setData(model: RouteLineModel) {
        setCollect(model.collectionnum)
        setPraise(model.praisenum)

        viewBinding.detail.ivCollect.setImageResource(if (model.iscollection) R.mipmap.ic_heart_selected else R.mipmap.ic_heart_unselected)
        viewBinding.detail.ivPrice.setImageResource(if (model.ispraise) R.mipmap.ic_like_selected else R.mipmap.ic_like_unselected)

        viewBinding.detail.collection.setOnClickListener {
            if (model.iscollection) {
                routeLineViewModel.cancelCollect(model.id) {
                    model.iscollection = !model.iscollection
                    setCollect(if (model.collectionnum<=1) 0 else (model.collectionnum-1))
                    viewBinding.detail.ivCollect.setImageResource(R.mipmap.ic_heart_unselected)
                }
            } else {
                routeLineViewModel.collect(model.id) {
                    model.iscollection = !model.iscollection
                    setCollect(model.collectionnum+1)
                    viewBinding.detail.ivCollect.setImageResource(R.mipmap.ic_heart_selected)
                }
            }
        }
        viewBinding.detail.praise.setOnClickListener {
            if (model.ispraise) {
                routeLineViewModel.cancelPraise(model.id) {
                    model.ispraise = !model.ispraise
                    setPraise(if (model.praisenum<=1) 0 else (model.praisenum-1))
                    viewBinding.detail.ivPrice.setImageResource(R.mipmap.ic_like_unselected)
                }
            } else {
                routeLineViewModel.praise(model.id) {
                    model.ispraise = !model.ispraise
                    setPraise(model.praisenum+1)
                    viewBinding.detail.ivPrice.setImageResource(R.mipmap.ic_like_selected)
                }
            }
        }
        viewBinding.titlebar.tvTitle.text = model.name
        viewBinding.recyclerView.adapter = CommentAdapter().apply {
            setNewInstance(model.comments?.toMutableList())
        }
        setCommentCount(model.comments?.size ?: 0)
        viewBinding.detail.img.adapter = ImageAdapter(model.allImages)
        val chartA = viewBinding.detail.highlyChart.attChar
        model.highly?.let {
            chartA.setHoriItems(it.x?.map {
                it.toString()
            }?.let { it1 -> ArrayList(it1) })
            chartA.setItems(
                arrayListOf(
                    ChartLineItem(
                        ArrayList(it.data),
                        R.color.teal_200,
                        "Climb",
                        false,
                        false
                    )
                )
            )

//            chartA.setHoriItems(arrayListOf("2","4","8"))
//            chartA.setItems(arrayListOf(ChartLineItem(arrayListOf(10.0,12.0,50.0),R.color.teal_200,"Climb",false,false)))
            viewBinding.detail.highlyChart.tvAtt.text =
                getString(R.string.leiji_pasheng, model.climb ?: "0")
        }
        viewBinding.detail.name.text = model.name
        viewBinding.detail.des.text = model.content
        viewBinding.detail.totalKm.text =
            getString(
                R.string.total_km_detail,
                (model.actualdistance / 1000f).toBigDecimal().setScale(3, RoundingMode.DOWN)
                    .toDouble().toString()
            )
        val distance = (mapViewModel.lastRecordPoint?.distance(
            Point.fromLngLat(
                model.startlng?.toDoubleOrNull() ?: 0.0, model.startlat?.toDoubleOrNull() ?: 0.0
            )
        ) ?: 0.0)
        viewBinding.detail.distanceTo.text = getString(
            R.string.distance_to_ride,
            (distance).toBigDecimal().setScale(3, RoundingMode.DOWN).toDouble().toString()
        )
        viewBinding.naviToStart.isEnabled = true
        viewBinding.startRide.isEnabled = true
        if (distance >= 0.02) {
            viewBinding.naviToStart.visibility = View.VISIBLE
            viewBinding.startRide.visibility = View.GONE
        } else {
            viewBinding.naviToStart.visibility = View.GONE
            viewBinding.startRide.visibility = View.VISIBLE
        }
        viewBinding.naviToStart.setOnClickListener {
            val lineStart = Point.fromLngLat(
                model.startlng?.toDoubleOrNull() ?: 0.0,
                model.startlat?.toDoubleOrNull() ?: 0.0
            )
            val end = Point.fromLngLat(
                model.endlng?.toDoubleOrNull() ?: 0.0,
                model.endlat?.toDoubleOrNull() ?: 0.0
            )
            toStart = true
            endPoint = end
            val repository = MapRepository()
            lifecycleScope.launch {
                val myStart =
                    mapViewModel.lastRecordPoint ?: repository.location()?.toPoint()
                if (myStart == null) {
                    return@launch
//                    location(lineStart, end)
                    return@launch
                }
                navigate(myStart, lineStart, end)
            }

        }

        viewBinding.startRide.setOnClickListener {
            model.json?.apply {
                mapViewModel.setPoints(ArrayList(this))
                MainActivity.toMain(this@RouteLineDetailActivity, 2)
            }
//            toStart = false
//            val end = Point.fromLngLat(
//                model.endlng?.toDoubleOrNull() ?: 0.0,
//                model.endlat?.toDoubleOrNull() ?: 0.0
//            )
////            navigate(
////                Point.fromLngLat(
////                    model.startlng?.toDoubleOrNull() ?: 0.0,
////                    model.startlat?.toDoubleOrNull() ?: 0.0
////                ), end
////            )
//
//            val start = Point.fromLngLat(
//                model.startlng?.toDoubleOrNull() ?: 0.0,
//                model.startlat?.toDoubleOrNull() ?: 0.0
//            )
//            toStart = false
//            endPoint = end
//            navigate(start, end)
////            val start = mapViewModel.lastRecordLocation?.toPoint()
//            if (start == null) {
//                location(end)
//                return@setOnClickListener
//            }

        }
    }

    var toStart = false

    private var endPoint: Point? = null

    fun setCommentCount(count: Int) {
        viewBinding.commentCount.text = getString(R.string.comment_count, count)
        if (count <= 0) {
            viewBinding.recyclerView.visibility = View.GONE
            viewBinding.emptyText.visibility = View.VISIBLE
            viewBinding.commentLl.layoutParams = viewBinding.commentLl.layoutParams?.let {
                it.height = ViewGroup.LayoutParams.WRAP_CONTENT
                it
            }
        } else {
            viewBinding.emptyText.visibility = View.GONE
            viewBinding.recyclerView.visibility = View.VISIBLE
            viewBinding.commentLl.layoutParams = viewBinding.commentLl.layoutParams?.let {
                it.height = ViewGroup.LayoutParams.WRAP_CONTENT
                it
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    private fun navigate(myStart: Point, start: Point, end: Point) {
        showLoading()
        RouteMapView.mapboxNavigation.requestRoutes(
            RouteOptions.builder()
                .applyDefaultNavigationOptions(DirectionsCriteria.PROFILE_CYCLING)
                .coordinatesList(
                    listOf(
                        myStart,
                        start,
                        end
                    )
                ).build(), object : NavigationRouterCallback {
                override fun onCanceled(
                    routeOptions: RouteOptions,
                    routerOrigin: RouterOrigin
                ) {
                    hideDialog()
                }

                override fun onFailure(
                    reasons: List<RouterFailure>,
                    routeOptions: RouteOptions
                ) {
                    hideDialog()
                    showMessage("routes fail: ${reasons.firstOrNull()?.message}")
                }

                override fun onRoutesReady(
                    routes: List<NavigationRoute>,
                    routerOrigin: RouterOrigin
                ) {
                    hideDialog()
                    mapViewModel.setCurrentRoute(routes, start, end)
                    MainActivity.toMain(this@RouteLineDetailActivity, 2)
                }

            }
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1000) {
            if (resultCode == RESULT_OK) {
                viewBinding.naviToStart.isEnabled = false //已经到起点了
            }
        }
    }

    inner class CommentAdapter :
        BaseQuickAdapter<Comment, CommentViewHolder>(R.layout.list_item_comment) {
        override fun convert(holder: CommentViewHolder, item: Comment) {
            holder.vb.content.text = item.content
            holder.vb.time.text = item.createtime
            holder.vb.name.text = item.user?.name
            holder.vb.head.apply {
                loadHead(item.user?.avatar)
            }
            holder.vb.comment.setOnClickListener {
                recid = item.id.toString()
                AddCommentDialog(this@RouteLineDetailActivity, this@RouteLineDetailActivity).show()
            }
        }

    }

    inner class GailouCommentAdapter :
        BaseQuickAdapter<Comment, GailouCommentViewHolder>(R.layout.list_item_gailou_comment) {
        override fun convert(holder: GailouCommentViewHolder, item: Comment) {
            holder.vb.content.text = item.content
            holder.vb.time.text = item.createtime
            holder.vb.name.text = item.user?.nickname
            holder.vb.head.apply {
                loadHead(item.user?.avatar)
            }
        }

    }

    class GailouCommentViewHolder(view: View) : BaseViewHolder(view) {
        val vb = ListItemGailouCommentBinding.bind(view)
    }

    class CommentViewHolder(view: View) : BaseViewHolder(view) {
        val vb = ListItemCommentBinding.bind(view)
    }

    override fun callback(content: String) {
        showLoading()
        routeLineViewModel.addComment(data?.id ?: 0, recid, content) {
            hideDialog()
            load()
        }
    }
}